import { USERINFO } from '@/global/contants'
import { defineStore } from 'pinia'
import {
  postLoginByPhoneAndCode,
  postUserCertation,
  reqCertificatesType,
  reqGetCodeByPhone,
  reqGetUserInfo,
  reqGetUserPatientAll
} from '@/service/modules/user'
import type {
  IAllPatientDataArr,
  ICertificatesTypeArr,
  ILoginData,
  ILoginUserData,
  IUserInfoData,
  IUserParams
} from '@/service/modules/user/type'
import { localCache } from '@/utils/cache'
import { mapToMenu } from '@/utils/mapRouteToMenu'

interface IState {
  isShowLoginBox: boolean
  code: string
  userData: ILoginUserData
  patientsAll: IAllPatientDataArr
  menuList: any[]
  userInfoData: IUserInfoData
  certificatesTypeData: ICertificatesTypeArr
}
export const useUserStore = defineStore('user', {
  state: (): IState => ({
    isShowLoginBox: false,
    code: '',
    userData: localCache.getCache(USERINFO) || {},
    patientsAll: [],
    menuList: [],
    userInfoData: {} as IUserInfoData,
    certificatesTypeData: []
  }),
  actions: {
    changeLoginBoxState() {
      this.isShowLoginBox = !this.isShowLoginBox
      this.code = ''
    },
    // 通过路由获取user 的菜单
    fetUserMenuAction() {
      this.menuList = mapToMenu('user')
    },
    // 获取验证码
    async fetchGetCodeByPhoneAction(phone: string) {
      const res = await reqGetCodeByPhone(phone)
      if (res.code == 200) {
        this.code = res.data
      }
    },
    // 登录
    async fetchLoginByPhoneandCodeAction(loginParams: ILoginData) {
      const res = await postLoginByPhoneAndCode(loginParams)
      console.log(res)
      if (res.code == 200) {
        this.isShowLoginBox = false
        this.userData = res.data
        localCache.setCache(USERINFO, this.userData)
      } else {
        return new Error('登录失败！')
      }
    },
    // 退出登录
    fetchLoginOutAction() {
      this.userData = {
        name: '',
        token: ''
      }
      localCache.removeCache(USERINFO)
    },
    // 账户下的就诊人
    async fecthAllPatientsByUserAction() {
      const res = await reqGetUserPatientAll()
      if (res.code == 200) {
        this.patientsAll = res.data
      }
    },
    // 用户信息（实名认证判断）
    async fetchGetUserInfoAction() {
      const res = await reqGetUserInfo()
      if (res.code == 200) {
        this.userInfoData = res.data
      }
    },
    // 证件类型
    async fetchGetReqCertificatesType() {
      const res = await reqCertificatesType()
      if (res.code == 200) {
        this.certificatesTypeData = res.data
      }
    },
    // 实名认证
    async fetchUserAuthAction(config: IUserParams) {
      const res = await postUserCertation(config)
      if (res.code == 200) {
        ElMessage.success('认证成功！')
        this.fetchGetUserInfoAction()
      } else {
        ElMessage.error('认证失败！')
      }
    }
  }
})
